package streaming

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringSerializer
import org.apache.log4j.{Level, Logger}
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Producer {
  def main(args: Array[String]): Unit = {
    Logger.getLogger("org").setLevel(Level.ERROR)
    val conf = new SparkConf().setAppName(this.getClass.getCanonicalName.init).setMaster("local[*]")
    val sc = new SparkContext(conf)

    // 读取sample.log文件数据
    val lines: RDD[String] = sc.textFile("data/sample.log")

    // 定义 kafka producer参数
    val brokers = "linux121:9092,linux122:9092,linux123:9093"
    val prop = new Properties()
    prop.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers)
    prop.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, classOf[StringSerializer])
    prop.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, classOf[StringSerializer])


    //发送读取的文件内容到mytopic1
    lines.foreachPartition{
      iter=>
        val producer = new KafkaProducer[String, String](prop)
        iter.foreach{
          line=>
           val msg = new ProducerRecord[String,String]("mytopic1",line)
            producer.send(msg)
        }
        producer.close()
    }
  }
}
